package com.stu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stu.common.R;
import com.stu.pojo.Channel;
import com.stu.pojo.Clazz;
import com.stu.pojo.Student;
import com.stu.pojo.StudentDesc;
import com.stu.service.IChannelService;
import com.stu.service.IClazzService;
import com.stu.service.IStudentDescService;
import com.stu.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/channel")
public class ChannelController {

    @Autowired
    IChannelService channelService;
    @Autowired
    IStudentDescService studentDescService;
    @Autowired
    IStudentService studentService;

    @GetMapping
    public R getAllChannelName(){
        List<Channel> list = channelService.list();
        List<String> nameList = list.stream().map(Channel::getName).collect(Collectors.toList());
        return R.success(nameList);
    }
    //通过channel查询渠道中的学员
    @GetMapping("/student/{id}")
    public R getStudents(@PathVariable Long id){
        LambdaQueryWrapper<StudentDesc> qw = new LambdaQueryWrapper<>();
        qw.eq(StudentDesc::getChannelId,id);
        List<StudentDesc> list = studentDescService.list(qw);
        List<Student> students = new ArrayList<>();
        for (StudentDesc studentDesc : list) {
            Long sid = studentDesc.getSid();
            //查询学生信息
            LambdaQueryWrapper<Student> sqw = new LambdaQueryWrapper<>();
            sqw.eq(Student::getSid,sid);
            Student student1 = studentService.getOne(sqw);
            students.add(student1);
        }
        return R.success(students);
    }




    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name){
        Page<Channel> channelPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Channel> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(name),Channel::getName,name);
        qw.orderByDesc(Channel::getUpdateTime);
        qw.orderByAsc(Channel::getName);
        channelService.page(channelPage,qw);
        return R.success(channelPage);
    }

    @PostMapping
    public R save(@RequestBody Channel channel){
        channelService.save(channel);
        return R.success("新增成功");
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Long id){
        Channel channel = channelService.getById(id);
        if (channel != null){
            return R.success(channel);
        }
        return R.error("没有查询到对应渠道信息");
    }

    @PutMapping
    public R update(@RequestBody Channel channel){
        boolean flag = channelService.updateById(channel);
        return flag ? R.success("修改成功"):R.error("修改失败");
    }
}

